using System.Linq;

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;

using Volo.Abp.AspNetCore.Mvc.ExceptionHandling;

namespace NP.BPMReportPlatform.Filters
{
    public static class CustomWrappingServiceCollectionExtensions
    {
        public static IServiceCollection AddCustomWrapping(this IServiceCollection services)
        {
            services.PostConfigure<MvcOptions>(options =>
                options.ReplaceServiceFilter<AbpExceptionFilter, CustomExceptionFilter>()
            );
            return services;
        }

        private static MvcOptions ReplaceServiceFilter<TOriginal, TReplacement>(this MvcOptions options)
            where TOriginal : IFilterMetadata
            where TReplacement : IFilterMetadata
        {

            var originals = options.Filters.OfType<ServiceFilterAttribute>()
                .Where(filter => typeof(TOriginal).IsAssignableFrom(filter.ServiceType))
                .ToList();
            foreach (var original in originals)
            {
                options.Filters.Remove(original);
            }
            options.Filters.AddService<TReplacement>();
            return options;
        }
    }
}